package com.goldenlight.fvms.manager.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.goldenlight.fvms.manager.converter.CompareConverter;
import com.goldenlight.fvms.manager.entity.EmployFreeApply;
import com.goldenlight.fvms.manager.entity.FreeApply;
import com.goldenlight.fvms.manager.filter.*;
import com.goldenlight.fvms.manager.idgenerator.service.IdService;
import com.goldenlight.fvms.manager.service.EmployFreeApplyService;
import com.goldenlight.fvms.manager.service.FreeApplyService;
import com.goldenlight.fvms.manager.service.ProductFreeApplyService;
import com.goldenlight.fvms.manager.utils.CommonUtils;
import com.goldenlight.fvms.manager.utils.ExcelUtils;
import com.goldenlight.fvms.manager.vo.CompareVO;
import com.goldenlight.fvms.manager.vo.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文件上传和导出接口
 */

@RestController
@RequestMapping("/upload")
public class ExcelUploadController {
    private static Logger logger = LoggerFactory.getLogger(ExcelUploadController.class);
    @Autowired
    private EmployFreeApplyService employFreeApplyService;
    @Autowired
    private ProductFreeApplyService productFreeApplyService;
    @Autowired
    private FreeApplyService freeApplyService;
    @Autowired
    private IdService idService;
    @Autowired
    private CompareConverter compareConverter;

    @GetMapping("compareVersions")
    public Response compareByVersion(@RequestParam(name="oldVersion",required = false,defaultValue = "") String oldVersion,
                                     @RequestParam(name="newVersion") String newVersion) {
        List<CompareVO> result = new ArrayList<>();

        List<FreeApply> oldList = freeApplyService.list(new QueryWrapper<FreeApply>().lambda().eq(FreeApply::getBuildVersion, oldVersion));
        List<FreeApply> newList = freeApplyService.list(new QueryWrapper<FreeApply>().lambda().eq(FreeApply::getBuildVersion, newVersion));
        if (oldList.isEmpty()) {
            result.addAll(CommonUtils.convertList(newList, CompareVO.class));
            return Response.build(000, "success", result);
        }

        List<FreeApply> subtract = this.getSubtract(newList, oldList);//newList中独有的数据，差集（new-old）
        List<FreeApply> intersection = this.getIntersection(newList, oldList);//newList,oldList中共有的数据，交集，取newList数据

        result.addAll(CommonUtils.convertList(subtract, CompareVO.class));
        intersection.stream().forEach(item->
            oldList.stream().forEach(i->{
                if( item.getCarNum().equals(i.getCarNum()) && !item.getCarBussType().equals(i.getCarBussType())){
                    CompareVO compareVO = compareConverter.convertOld(i);
                    BeanUtils.copyProperties(item,compareVO);
                    result.add(compareVO);
                }
            })
        );
        logger.info("result:{}",result);
        return Response.build(000, "success",result);
    }

    /**
     * 差集 a-b
     * @param list
     * @param oldList
     * @return
     */
    private List<FreeApply> getSubtract(List<FreeApply> list, List<FreeApply> oldList) {
        return list.stream().filter(item -> {
            List<FreeApply> result = oldList.stream().filter(i -> i.getCarNum().equals(item.getCarNum())).collect(Collectors.toList());
            return result.size() <= 0;
        }).collect(Collectors.toList());
    }

    /**
     * 交集，取第一个参数中的元素
     * @param list
     * @param oldList
     * @return
     */
    private List<FreeApply> getIntersection(List<FreeApply> list, List<FreeApply> oldList) {
        return list.stream().filter(item -> {
            List<FreeApply> result = oldList.stream().filter(i -> i.getCarNum().equals(item.getCarNum())).collect(Collectors.toList());
            return result.size() > 0;
        }).collect(Collectors.toList());
    }

    @PostMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        List<Object> list = new ArrayList<>();
        ExcelUtils.exportExcel(list, "aa", "sheet1", Object.class, "w文件处理.xlsx", response);
    }

    @PostMapping("/upload")
    public Response upload(@RequestParam("file") MultipartFile file,
                           @RequestParam("data") Integer type,
                           @RequestParam("uuid")String uuid,
                           @RequestParam("companyId")Long[] companyId,
                           @RequestParam("buildVersion")String buildVersion) {
        logger.info("type:{},companyId:{},buildVersion{}", type, companyId,buildVersion);
        Request request = new Request();
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("file", file);
        map.put("logger", logger);
        map.put("uuid", uuid);
        map.put("companyId", companyId);

        map.put("idService", idService);
        map.put("buildVersion", buildVersion);
        map.put("parentService", freeApplyService);
        if(type==5) {
            map.put("service", employFreeApplyService);
            request.setData(map);
            com.goldenlight.fvms.manager.filter.Response response = new com.goldenlight.fvms.manager.filter.Response();
            FilterChain filterChain = new FreeApplyBuilder().addFilter(new EmployFreeCarApplyFilter()).build();
            filterChain.doFilter(request, response, filterChain);
            return Response.build(200, type.toString(), response.getResponse());
        }else{
            map.put("producService", productFreeApplyService);
            request.setData(map);
            com.goldenlight.fvms.manager.filter.Response response = new com.goldenlight.fvms.manager.filter.Response();
            FilterChain filterChain = new FreeApplyBuilder().addFilter(new ProductFreeCarApplyFilter()).build();
            filterChain.doFilter(request, response, filterChain);
            return Response.build(000, type.toString(), response.getResponse());
        }
    }





}
